﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using System.ComponentModel;
using zx;
using CustomAutoCompleteBox;

namespace GshopToolCS
{

	/// <summary>
	/// MainWindow.xaml 的交互逻辑
	/// </summary>
	public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
			//headerVM = new HeaderVM();
			//treeVM = new TreeVM();
			gshop15 = new GShop15();
			IDList = new List<string>();
			NameList = new List<string>();
		}

		/// <summary>
		/// 定义一系列ViewModel
		/// </summary>
		//public HeaderVM headerVM;

		//public TreeVM treeVM;

		/// <summary>
		/// 诛仙15职业数据结构
		/// </summary>
		private GShop15 gshop15;

		/// <summary>
		/// AutoCompleteBox Source
		/// </summary>
		private List<string> IDList;
		private List<String> NameList;

		

		/// <summary>
		/// 更新headerTextBox数据
		/// </summary>
		private void UpdateHeaderTextBox()
		{
			this.headerTextBox.Text = "";
			headerTextBox.Text = Convert.ToString(gshop15.TimeStamp);
		}

		/// <summary>
		/// 更新treeView数据
		/// </summary>
		private void UpdateTreeView()
		{
			treeView.Items.Clear();

			if(gshop15.FirstClassList.Count<=0)
			{
				return;
			}

			foreach (var firstClass in gshop15.FirstClassList)
			{
				TreeViewItem fcItem = new TreeViewItem();
				fcItem.Header = System.Text.Encoding.Unicode.GetString(firstClass.FirstClassName).TrimEnd('\0');
				foreach (var secondClassName in firstClass.SecondClassNameList)
				{
					TreeViewItem scItem = new TreeViewItem();
					scItem.Header= System.Text.Encoding.Unicode.GetString(secondClassName).TrimEnd('\0');
					fcItem.Items.Add(scItem);
				}
				treeView.Items.Add(fcItem);
			}

			foreach (var item in gshop15.ItemList)
			{
				TreeViewItem childItem = new TreeViewItem();
				childItem.Header = System.Text.Encoding.Unicode.GetString(item.Name).TrimEnd('\0');
				childItem.Tag = item.ID;
				var fcItem = treeView.Items.GetItemAt(item.Class1) as TreeViewItem;
				var scItem = fcItem.Items.GetItemAt(item.Class2) as TreeViewItem;
				scItem.Items.Add(childItem);
			}
		}

		/// <summary>
		/// 更新两个AutoCompleteBox数据源
		/// </summary>
		private void UpdateAutoCompleteBox()
		{
			foreach (var item in gshop15.ItemList)
			{
				IDList.Add(item.ID.ToString());
				//NameList.Add(new string(item.Name));
				NameList.Add(System.Text.Encoding.Unicode.GetString(item.Name).TrimEnd('\0'));
			}
			
			this.itemIDACB.SourceList = IDList;
			this.itemNameACB.SourceList = NameList;
		}

		private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem item = sender as MenuItem;

            if(item.Name=="openMenu")
            {
				///<summary>
				/// 打开文件并读取
				/// </summary>

				OpenFileDialog openDialog = new OpenFileDialog();
                openDialog.DefaultExt = "*.data";
                openDialog.Filter = "gshop.data|*.data|所有文件（*.*）|*.*";
                if (openDialog.ShowDialog() == true) 
                {
					try
					{
						GShop15.VerifyVersion(openDialog.FileName);
					}
					catch (Exception exp)
					{

						MessageBox.Show(exp.Message);
						return;
					}
					try
					{
						gshop15.Load(openDialog.FileName);
					}
					catch (Exception err)
					{

						Xceed.Wpf.Toolkit.MessageBox.Show("无法识别的版本，错误提示：\n" + err.StackTrace);
						return;
					}

					//开始设置ViewModl				
					//headerTextBox.DataContext = new HeaderVM(gshop15);
					UpdateHeaderTextBox();
					UpdateTreeView();
					UpdateAutoCompleteBox();
					this.Title = "GShopTool v1.0 --" + openDialog.FileName;
					//Xceed.Wpf.Toolkit.MessageBox.Show("读取完毕！");
				}



			}
            else if(item.Name=="saveMenu")
            {
				if (treeView.Items.Count < 0) 
				{
					return;
				}
				SaveFileDialog saveDialog = new SaveFileDialog();
				saveDialog.DefaultExt = "*.data";
				saveDialog.Filter= "gshopNew.data|*.data|所有文件（*.*）|*.*";
				saveDialog.OverwritePrompt = true;
				saveDialog.ValidateNames = true;
				if (saveDialog.ShowDialog() == true) 
				{
					gshop15.Save(saveDialog.FileName);

					//保存完了，再顺便打开
					Title = "GShopTool v1.0 --" + saveDialog.FileName;
				}
			}
            else if(item.Name=="exitMenu")
            {
                Close();
            }
          
        }

		/// <summary>
		/// 修改文件头
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void modifyHeaderBtn_Click(object sender, RoutedEventArgs e)
		{
			Image img = this.showIconImage;

			Xceed.Wpf.Toolkit.MessageBox.Show(img.Source.ToString());
		}

		private void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
		{
			TreeViewItem treeItem = this.treeView.SelectedItem as TreeViewItem;

			//如果treeItem有子项，说明不是大类就是小类，只需要设置NameACB
			if (treeItem.Items.Count > 0) 
			{
				rightStackPanel.DataContext = null;
				itemNameACB.SetCurrentValue(TextBox.TextProperty, treeItem.Header.ToString());
			}
			else
			{
				int treeItemTagInt = Convert.ToInt32(treeItem.Tag);
				foreach (var item in gshop15.ItemList)
				{
					if (treeItemTagInt == item.ID && treeItem.Header.ToString() == System.Text.Encoding.Unicode.GetString(item.Name).TrimEnd('\0'))
					{
						this.rightStackPanel.DataContext = item;
						break;
					}
				}
			}			
		}

		private void searchIDBtn_Click(object sender, RoutedEventArgs e)
		{
			//treeView为空，则不用搜索了
			if(treeView.Items.IsEmpty)
			{
				return;
			}
			try
			{
				int id = Int32.Parse(this.itemIDACB.Text);
				var item = gshop15.GetItemByID(id);
				this.rightStackPanel.DataContext = item;

				/// <summary>
				/// 标识符，是否跳出下面的循环
				/// </summary>
				bool isBreak = false;

				//设置TreeView选中项				
				foreach (var firstNode in treeView.Items)
				{
					if(isBreak)
					{
						break;
					}
					foreach (var secondNode in (firstNode as TreeViewItem).Items)
					{
						if(isBreak)
						{
							break;
						}
						foreach (var childNode in (secondNode as TreeViewItem).Items)
						{
							int tagID = Convert.ToInt32((childNode as TreeViewItem).Tag);
							if (tagID == id)
							{
								(childNode as TreeViewItem).IsSelected = true;
								(secondNode as TreeViewItem).IsExpanded = true;
								(firstNode as TreeViewItem).IsExpanded = true;

								
								isBreak = true;
								break;
							}
						}
					}
				}			
			}
			catch (Exception exp)
			{
				MessageBox.Show(exp.Message);				
			}
		}

		/// <summary>
		/// 根据ID，递归遍历整个TreeView
		/// </summary>
		/// <param name="treeViewItem"></param>
		/// <param name="tagID"></param>
		private void SetTreeViewItemSelected(TreeViewItem treeViewItem,int tagID)
		{
			if (treeViewItem.Items.Count > 0) 
			{
				foreach (var item in treeViewItem.Items)
				{
					SetTreeViewItemSelected(item as TreeViewItem, tagID);
				}
			}
			else
			{
				int id = Convert.ToInt32(treeViewItem.Tag);
				if (tagID == id)
				{					
					treeViewItem.IsSelected = true;
					TreeViewItem parent = treeViewItem.Parent as TreeViewItem;
					parent.IsExpanded = true;
					TreeViewItem parentParent = parent.Parent as TreeViewItem;
					parentParent.IsExpanded = true;
				}
			}

		}


		private void searchNameBtn_Click(object sender, RoutedEventArgs e)
		{

			if (treeView.Items.IsEmpty)
			{
				return;
			}
			try
			{
				var item = gshop15.GetItemByName(itemNameACB.Text);
				this.rightStackPanel.DataContext = item;

				/// <summary>
				/// 标识符，是否跳出下面的循环
				/// </summary>
				bool isBreak = false;

				//设置TreeView选中项				
				foreach (var firstNode in treeView.Items)
				{
					if (isBreak)
					{
						break;
					}
					foreach (var secondNode in (firstNode as TreeViewItem).Items)
					{
						if (isBreak)
						{
							break;
						}
						foreach (var childNode in (secondNode as TreeViewItem).Items)
						{
							if ((childNode as TreeViewItem).Header.ToString() == itemNameACB.Text) 
							{
								(childNode as TreeViewItem).IsSelected = true;
								(secondNode as TreeViewItem).IsExpanded = true;
								(firstNode as TreeViewItem).IsExpanded = true;							
								isBreak = true;
								break;
							}
						}
					}
				}
			}
			catch (Exception exp)
			{
				MessageBox.Show(exp.Message);
			}
		}

		private void PreViewBtn_Click(object sender, RoutedEventArgs e)
		{
			DescriptionPreviewWindow dpw = new DescriptionPreviewWindow();
			dpw.SetText(itemDescriptionTextBox.Text);
			dpw.ShowDialog();
		}

		private void awardPreviewBtn_Click(object sender, RoutedEventArgs e)
		{
			DescriptionPreviewWindow dpw = new DescriptionPreviewWindow();
			dpw.SetText(awardDescriptionTextBox.Text);
			dpw.ShowDialog();
		}
	}




	/// <summary>
	/// 实现INotifyPropertyChanged接口
	/// </summary>
	public abstract class NotificationObject: INotifyPropertyChanged
	{
		public event PropertyChangedEventHandler PropertyChanged;

		protected virtual void RaisePropertyChanged(string propertyName)
		{
			if(PropertyChanged!=null)
			{
				this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
			}
		}
	}

	/// <summary>
	/// 文件头ViewModel
	/// </summary>
	public class HeaderVM : NotificationObject
	{
		public HeaderVM()
		{
			gshop = new GShop15();
		}

		public HeaderVM(GShop15 value)
		{
			gshop = value;
			//RaisePropertyChanged("GShopTimeStamp");
		}

		private GShop15 gshop;
		public int GShopTimeStamp
		{
			get
			{
				return gshop.TimeStamp;
			}
			set
			{
				gshop.TimeStamp = value;
				RaisePropertyChanged("GShopTimeStamp");
			}
		}

	}

	/// <summary>
	/// 树形框ViewModel
	/// </summary>
	//public class TreeVM : NotificationObject
	//{
	//	public TreeVM()
	//	{
	//		gshop = new GShop15();
	//		firstClassList = new List<FirstClass>();
	//		Class1List = new List<Class1>();
	//	}
		
	//	public TreeVM(GShop15 value)
	//	{
	//		Class1List = new List<Class1>();
	//		gshop = value;

	//		foreach (var item1 in gshop.FirstClassList)
	//		{
	//			Class1 class1 = new Class1();
	//			class1.Name = System.Text.Encoding.Unicode.GetString(item1.FirstClassName).TrimEnd('\0');

	//			foreach (var item2 in item1.SecondClassNameList)
	//			{
	//				Class2 class2 = new Class2();
	//				class2.Name= System.Text.Encoding.Unicode.GetString(item2).TrimEnd('\0');
	//				class1.Class2List.Add(class2);
	//			}
	//			Class1List.Add(class1);
	//		}
	//	}
	//	private GShop15 gshop;


	//	public List<Class1> Class1List { get; set; }



	//	private List<FirstClass> firstClassList;


	//	/// <summary>
	//	/// 商品大类
	//	/// </summary>
	//	public List<string> FirstClassNameList
	//	{
	//		get
	//		{
	//			List<string> name = new List<string>();
	//			foreach (var item in gshop.FirstClassList)
	//			{
	//				name.Add(System.Text.Encoding.Unicode.GetString(item.FirstClassName).TrimEnd('\0'));
	//			}
	//			return name;
	//		}
	//		set
	//		{
	//			RaisePropertyChanged("FirstClassNameList");
	//		}
	//	}

	//	/// <summary>
	//	/// 商品小类
	//	/// </summary>
	//	public List<List<string>> SecondClassNameList
	//	{
	//		get
	//		{
	//			List<List<string>> nameList1 = new List<List<string>>();
	//			foreach (var item1 in gshop.FirstClassList)
	//			{
	//				List<string> nameList2 = new List<string>();
	//				foreach (var item2 in item1.SecondClassNameList)
	//				{
	//					nameList2.Add(System.Text.Encoding.Unicode.GetString(item2).TrimEnd('\0'));
	//				}
	//				nameList1.Add(nameList2);
	//			}
	//			return nameList1;
	//		}
	//		set
	//		{
	//			RaisePropertyChanged("SecondClassNameList");
	//		}
	//	}

	//	public class Class1
	//	{
	//		public Class1()
	//		{
	//			Class2List = new List<Class2>();
	//		}

	//		public string Name { get; set; }
	//		public List<Class2> Class2List { get; set; }
	//	}

	//	public class Class2
	//	{
	//		public string Name { get; set; }
	//		//public List<ITEM> itemList { get; set; }
	//	}
	//}


}

